package com.ffmpeg.opt.common.ffmpeg;

import com.ffmpeg.opt.common.ffmpeg.data.CommandTasker;
import com.ffmpeg.opt.common.ffmpeg.handler.MovieCovertHandlerMethod;
import com.ffmpeg.opt.common.ffmpeg.handler.MovieTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 全局fmpeg处理
 *
 * @author: 李涛
 * @version: 2020年05月17日 14:07
 */
@Component
@Slf4j
public class FmpegUtil {

    private static final CommandManager command = new CommandManagerImpl(new MovieCovertHandlerMethod());

    /**
     * 开始任务
     *
     * @param commond
     * @return
     */
    public String start(String commond, MovieTask movieTask) {
        log.info("命令:{}", commond);
        String start = command.start(movieTask.getTaskId(), commond, true);
        MovieCovertHandlerMethod.taskBean.put(start, movieTask);
        return start;
    }

    /**
     * 停止任务
     *
     * @param taskId
     * @return
     */
    public boolean stop(String taskId) {
        boolean stop = command.stop(taskId);
        return stop;
    }

    /**
     * 查看进度
     *
     * @param taskId
     * @return
     */
    public CommandTasker query(String taskId) {
        return command.query(taskId);
    }

    /**
     * 查看进度
     *
     * @param taskId
     * @return
     */
    public void waitDone(String taskId) {
        CommandTasker query = command.query(taskId);
        if (query != null) {
            try {
                query.getProcess().waitFor();
                MovieTask movieTask = MovieCovertHandlerMethod.taskBean.get(taskId);
                log.info("进程结束：{}", movieTask.toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查看进度
     *
     * @param taskId
     * @return
     */
    public String queryProgress(String taskId) {
        MovieTask movieTask = MovieCovertHandlerMethod.taskBean.get(taskId);
        if(movieTask==null){
            return "任务已完成";
        }
        double proess = movieTask.getProess();
        return movieTask.getTaskType() +" "+ proess + "%";
    }


}
